<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;

/**
 * 库存管理
 * @icon fa fa-cubes
 */
class Stock extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Stock;
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['material', 'warehouse', 'location'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            return json(["total" => $list->total(), "rows" => $list->items()]);
        }
        return $this->view->fetch();
    }

    /**
     * 库存预警
     */
    public function alert()
    {
        if ($this->request->isAjax()) {
            $alerts = Db::name('scanwork_stock_alert_log')
                ->alias('a')
                ->join('scanwork_material m', 'a.material_id = m.id')
                ->join('scanwork_warehouse w', 'a.warehouse_id = w.id', 'LEFT')
                ->where('a.is_handled', 0)
                ->field('a.*, m.material_name, w.warehouse_name')
                ->order('a.createtime', 'desc')
                ->select();
            return json(['code' => 1, 'data' => $alerts]);
        }
        return $this->view->fetch();
    }
}

